# routers/user.py
# 用户相关接口：注册、登录、资料、商家切换
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from schemas import UserCreate, UserOut
from models import User
from crud import get_user_by_username, get_user_by_email, create_user, verify_password
from deps import get_db
from pydantic import EmailStr

router = APIRouter(prefix="/user", tags=["用户"])

@router.post("/register", response_model=UserOut)
def register(user: UserCreate, db: Session = Depends(get_db)):
    """用户注册"""
    if get_user_by_username(db, user.username):
        raise HTTPException(status_code=400, detail="用户名已存在")
    if get_user_by_email(db, user.email):
        raise HTTPException(status_code=400, detail="邮箱已注册")
    return create_user(db, user)

@router.post("/login/{username}")
def login(username: str, password: str, db: Session = Depends(get_db)):
    """用户登录，返回简单信息（可扩展JWT）"""
    db_user = get_user_by_username(db, username)
    if not db_user or not verify_password(password, db_user.hashed_password):
        raise HTTPException(status_code=400, detail="用户名或密码错误")
    return {"id": db_user.id, "username": db_user.username, "is_seller": db_user.is_seller}

@router.get("/profile/{user_id}", response_model=UserOut)
def get_profile(user_id: int, db: Session = Depends(get_db)):
    """获取用户资料"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.post("/switch_seller")
def switch_seller(user_id: int, db: Session = Depends(get_db)):
    """切换为商家模式"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    user.is_seller = True
    db.commit()
    return {"msg": "切换为商家成功"} 